#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.careInfoController import CareInfoController
from models.careInfoModel import CareInfo
from models.userInfoModel import UserInfo
from models.passageInfoModel import PassageInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
from utils.validate_operate import verify_operator_object
from controller.userInfoController import UserInfoController


class CareInfoService(CareInfoController):
    @classmethod
    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('CareUserID'):
                filter_list.append(cls.CareUserID == kwargs.get('CareUserID'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            careInfo_info = db.session.query(CareInfo.UserID, CareInfo.CareUserID, CareInfo.CreateTime,
                                             CareInfo.IsDelete).filter(*filter_list)

            count = careInfo_info.count()
            pages = math.ceil(count / size)
            careInfo_info = careInfo_info.limit(size).offset((page - 1) * size).all()

            if not careInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(careInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def addcare(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('CareUserID'):
                filter_list.append(cls.CareUserID == kwargs.get('CareUserID'))

            careInfo_info = db.session.query(CareInfo.UserID, CareInfo.CareUserID, CareInfo.CreateTime,
                                             CareInfo.IsDelete).filter(*filter_list)
            careInfo_info = careInfo_info.first()
            if careInfo_info:
                return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST], 'error': 'Data has exists in DB'}

            # 二次查询减少数据冗余
            filter_list = [cls.IsDelete == 1, cls.UserID == kwargs.get('UserID'),
                           cls.CareUserID == kwargs.get('CareUserID')]
            reback_data = db.session.query(cls).filter(*filter_list)
            reback_data = reback_data.all()
            if reback_data:
                reback_data = commons.query_to_dict(reback_data)
                reback_data = {
                    'AutoID': reback_data[0].get('AutoID'),
                    'IsDelete': 0
                }
                cls.update(**reback_data)
                return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                        'data': 'reback care successfully'}
            # 处理返回的数据
            results = cls.add(**kwargs)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                    'data': results.get('data')}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()



    @classmethod
    def getcare(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('CareUserID'):
                filter_list.append(cls.CareUserID == kwargs.get('CareUserID'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            careInfo_info = db.session.query(CareInfo.CareUserID, UserInfo.FaceImg, UserInfo.UserNickName,PassageInfo.AutoID,
                                             PassageInfo.PostType, PassageInfo.UpVoteNum, PassageInfo.CommentNum,
                                             PassageInfo.LookNUM, PassageInfo.PostTitle, PassageInfo.CreateTime).join(
                UserInfo, UserInfo.UserID == CareInfo.CareUserID).join(PassageInfo,
                                                                       PassageInfo.PostAuthorID == UserInfo.UserID).filter(
                *filter_list).order_by(PassageInfo.CreateTime.desc())

            count = careInfo_info.count()
            pages = math.ceil(count / size)
            careInfo_info = careInfo_info.limit(size).offset((page - 1) * size).all()

            if not careInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(careInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    @verify_operator_object([99, ], UserInfoController)
    def getcarelist(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('CareUserID'):
                filter_list.append(cls.CareUserID == kwargs.get('CareUserID'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            careInfo_info = db.session.query( CareInfo.CareUserID, UserInfo.UserNickName,
                                             UserInfo.FaceImg, UserInfo.IsDelete
                                             ).join(UserInfo, UserInfo.UserID == CareInfo.CareUserID).filter(
                *filter_list).order_by(cls.CreateTime.desc())

            count = careInfo_info.count()
            pages = math.ceil(count / size)
            careInfo_info = careInfo_info.limit(size).offset((page - 1) * size).all()

            if not careInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(careInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def getsinglecare(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('CareUserID'):
                filter_list.append(cls.CareUserID == kwargs.get('CareUserID'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            careInfo_info = db.session.query(CareInfo.CareUserID, UserInfo.FaceImg, UserInfo.UserNickName,PassageInfo.AutoID,
                                             PassageInfo.PostType, PassageInfo.UpVoteNum, PassageInfo.CommentNum,
                                             PassageInfo.LookNUM, PassageInfo.PostTitle, PassageInfo.CreateTime).join(
                UserInfo, UserInfo.UserID == CareInfo.CareUserID).join(PassageInfo,
                                                                       PassageInfo.PostAuthorID == UserInfo.UserID).filter(
                *filter_list).order_by(PassageInfo.CreateTime.desc())

            count = careInfo_info.count()
            pages = math.ceil(count / size)
            careInfo_info = careInfo_info.limit(size).offset((page - 1) * size).all()

            if not careInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(careInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
